<template>
  <div>
    <el-card  class="mt-4">
      <template #header>
        <div class="card-header flex justify-between items-center">
          <span class="text-sm text-gray-500 font-semibold">订单统计</span>
          <div class="tags" v-for="item in options" :key="item.type">
            <el-check-tag
              :checked="currentType === item.type"
              @click="tagClick(item.type)"
              class="cursor-pointer"
              >{{ item.text }}</el-check-tag
            >
          </div>
        </div>
      </template>
      <div id="chart" style="width: 100%; height: 300px;" ref="el"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted,useTemplateRef,onBeforeUnmount} from "vue";
import { useResizeObserver } from '@vueuse/core'
import * as echarts from "echarts";
import {getStatistics3} from '@/api/index'
const currentType = ref("week");

const tagClick = (type) => {
  currentType.value = type;
  getData();
};
const options = [
  {
    text: "近一个月",
    type: "month",
  },
  {
    text: "近一周",
    type: "week",
  },
  {
    text: "近24小时",
    type: "hour",
  },
];


//在onMounted函数内部执行渲染图表的方法，因为要获取到chart节点元素
onMounted(() => {
  chartDom = document.getElementById("chart");
  myChart = echarts.init(chartDom);
  getData();
});

//在页面销毁之前将图标销毁掉
onBeforeUnmount(() => {
  myChart.dispose();
})

//监控大小变化
const el = useTemplateRef('el')
useResizeObserver(el, (entries) => {
  myChart.resize({
    width: entries[0].contentRect.width,
    height: entries[0].contentRect.height,
  })
})
var chartDom;
var myChart;
const getData = () => {
  let option = {
    xAxis: {
      type: "category",
      data: [],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [],
        type: "bar",
      },
    ],
  };

  myChart.showLoading();
  getStatistics3(currentType.value).then(res => {
    console.log(res);
    option.xAxis.data = res.x;
    option.series[0].data= res.y;
    option && myChart.setOption(option);
  }).finally(() => {
    myChart.hideLoading();
  })

};
</script>

<style lang="less" scoped>
</style>
